import defaultSettings from '@/settings'

// 定义设置的状态类型
interface SettingsState {
  title: string
  theme: string
  sideTheme: string
  showSettings: boolean
  topNav: boolean
  tagsView: boolean
  fixedHeader: boolean
  sidebarLogo: boolean
  dynamicTitle: boolean
}

const { sideTheme, showSettings, topNav, tagsView, fixedHeader, sidebarLogo, dynamicTitle } =
  defaultSettings

// 安全地解析本地存储的设置
let storageSetting: Partial<SettingsState> = {}
try {
  const settingStr = localStorage.getItem('layout-setting')
  if (settingStr) {
    storageSetting = JSON.parse(settingStr)
  }
} catch (err) {
  console.error('解析布局设置失败:', err)
  // 如果解析失败，使用空对象作为回退
  storageSetting = {}
}

const state: SettingsState = {
  title: '',
  theme: typeof storageSetting.theme === 'string' ? storageSetting.theme : '#409EFF',
  sideTheme: typeof storageSetting.sideTheme === 'string' ? storageSetting.sideTheme : sideTheme,
  showSettings: showSettings,
  topNav: typeof storageSetting.topNav === 'boolean' ? storageSetting.topNav : topNav,
  tagsView: typeof storageSetting.tagsView === 'boolean' ? storageSetting.tagsView : tagsView,
  fixedHeader:
    typeof storageSetting.fixedHeader === 'boolean' ? storageSetting.fixedHeader : fixedHeader,
  sidebarLogo:
    typeof storageSetting.sidebarLogo === 'boolean' ? storageSetting.sidebarLogo : sidebarLogo,
  dynamicTitle:
    typeof storageSetting.dynamicTitle === 'boolean' ? storageSetting.dynamicTitle : dynamicTitle,
}

const mutations = {
  CHANGE_SETTING: (state: SettingsState, { key, value }: { key: string; value: any }) => {
    if (key && state.hasOwnProperty(key)) {
      // 根据不同的设置项进行类型检查
      switch (key) {
        case 'theme':
        case 'sideTheme':
          if (typeof value === 'string') {
            state[key] = value
          }
          break
        case 'showSettings':
        case 'topNav':
        case 'tagsView':
        case 'fixedHeader':
        case 'sidebarLogo':
        case 'dynamicTitle':
          if (typeof value === 'boolean') {
            state[key] = value
          }
          break
        case 'title':
          if (typeof value === 'string') {
            state[key] = value
          }
          break
        default:
          break
      }
    }
  },
}

type Commit = <T>(type: string, payload?: T) => void

const actions = {
  // 修改布局设置
  changeSetting({ commit }: { commit: Commit }, data: { key: string; value: any }) {
    commit('CHANGE_SETTING', data)
  },
  // 设置网页标题
  setTitle({ commit }: { commit: Commit }, title: string) {
    state.title = title
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
